package com.huaxin.hxcloud.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.RepairTaskInfo;
import com.huaxin.common.Entity.RepairUPDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.common.utils.SpacesItemDecoration;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.Adapter.HorizontalRepairAdapter;
import com.huaxin.hxcloud.Adapter.RepairupCheckAdapter;
import com.huaxin.hxcloud.R;
import com.huaxindata.im.main.manager.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author lwjing
 * @date 2018/3/29
 * @Desc $desc$
 * Copyright HUAXIN DATA. All rights reserved.
 */
public class HxRepairUpCheckActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar      mToolbar;
    @BindView(R.id.more)
    TextView     more;
    @BindView(R.id.tv_task_code)
    TextView     tv_task_code;
    @BindView(R.id.tv_begin_time)
    TextView     tv_begin_time;
    @BindView(R.id.tv_worker)
    TextView     tv_worker;
    @BindView(R.id.tv_task_name)
    TextView     tv_task_name;
    @BindView(R.id.ll_worker)
    LinearLayout ll_worker;
    @BindView(R.id.tv_time_task_done)
    TextView     tv_time_task_done;
    @BindView(R.id.tv_task_duration)
    TextView     tv_task_duration;
    @BindView(R.id.rl_station_xunjian)
    RecyclerView rl_horizontal_Station;
    @BindView(R.id.rl_task_xunjian)
    RecyclerView rl_task;
    List<RepairUPDTO.RepairStation> stationArr = new ArrayList<>();
    List<RepairTaskInfo>            taskItems  = new ArrayList<>();
    private RepairupCheckAdapter    taskAdapter;
    private HorizontalRepairAdapter horizongtalStationAdapter;
    private String                  repairId;
    private int currentPos = 0;
    private HxSationDialogFragment mDialogFrament;
    private String                 taskId;
    private int                    taskType;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_repairup_check;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_CUNJIAN_ID)) {
            repairId = extras.getString(Constants.IK_CUNJIAN_ID);
            taskId = extras.getString(Constants.IK_TASK_ID);
            taskType = extras.getInt(Constants.IK_TASK_TYPE);
        } else {
            finish();
        }
    }

    @Override
    public void initView() {
        //super.initView();
        setSupportActionBar(mToolbar);
        if (taskType == 4) {
            mToolbar.setTitle("维修保养单审核");
            more.setText("审核");
        } else {
            mToolbar.setTitle("维修保养");
            more.setText("确认");
        }
        LinearLayoutManager horizontalMa = new LinearLayoutManager(this);
        horizontalMa.setOrientation(LinearLayoutManager.HORIZONTAL);
        rl_horizontal_Station.setLayoutManager(horizontalMa);
        horizongtalStationAdapter = new HorizontalRepairAdapter(R.layout.item_string, stationArr);
        rl_horizontal_Station.setAdapter(horizongtalStationAdapter);
        LinearLayoutManager verticalMa = new LinearLayoutManager(this);
        rl_task.setLayoutManager(verticalMa);
        taskAdapter = new RepairupCheckAdapter(R.layout.item_repairup_check, taskItems);
        rl_task.setAdapter(taskAdapter);
        rl_task.addItemDecoration(new SpacesItemDecoration(30));

        horizongtalStationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                //站点切换
                if (currentPos == position) {
                    return;
                }
                RepairUPDTO.RepairStation repairStation = stationArr.get(position);
                repairStation.setCheck(true);
                stationArr.get(currentPos).setCheck(false);
                horizongtalStationAdapter.notifyDataSetChanged();
                taskItems.clear();
                taskAdapter.setNewData(taskItems);
                //根据站点刷新任务列表
                taskItems.addAll(stationArr.get(position).getItem());
                taskAdapter.setNewData(taskItems);
                currentPos = position;
            }
        });
    }

    @Override
    protected void requestData() {
        //  super.requestData();
        apiArrangeTaskDetail();
    }

    private void apiArrangeTaskDetail() {
        updateLoadStatus(LOADING);
        Call<RepairUPDTO> call = HxTransmitRequestHelper.getRequestApi().getarrangeTaskDetail(repairId);
        autoClose(call);
        android.util.Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<RepairUPDTO>() {
            @Override
            public void onResponse(Call<RepairUPDTO> call, Response<RepairUPDTO> response) {
                RepairUPDTO repairUPDTO = response.body();
                if (response.isSuccessful() && repairUPDTO != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    //更新界面
                    updataView(repairUPDTO);
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<RepairUPDTO> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ---->" + t);
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }

    /**
     * 更新UI
     *
     * @param repairUPDTO
     */
    private void updataView(RepairUPDTO repairUPDTO) {
        RepairUPDTO.RepairUPBase repairUPBase = repairUPDTO.getData();
        if (repairUPBase == null) {
            updateLoadStatus(LOAD_NO_DATA);
            return;
        }
        //更新界面
        loadTextColon(tv_task_code, "工单编号", repairUPBase.getCode());
        if (repairUPBase.getFinishDate() != 0) {
            loadTextColon(tv_time_task_done, "截至时间", dateFormat(repairUPBase.getFinishDate()));
        }
        if (repairUPBase.getStartDate() != 0) {
            loadTextColon(tv_begin_time, "开始时间", dateFormat(repairUPBase.getStartDate()));
        }
        loadTextColon(tv_task_name, "工单名称", repairUPBase.getTitle());
        loadTextColon(tv_worker, "负责人", repairUPBase.getProposer());
        if (Constant.SPTOrgcodeFirst.equals(UserManager.getFirstOrgCode())) {
            tv_task_duration.setVisibility(View.INVISIBLE);
        }else{
            tv_task_duration.setVisibility(View.GONE);
        }
        loadTextColon(tv_task_duration, "绑定车辆", repairUPBase.getVehicleName());
        //默认选中第一个站点
        stationArr.addAll(repairUPBase.getStationArr());
        if (stationArr.size() > 0) {
            stationArr.get(0).setCheck(true);
        }
        horizongtalStationAdapter.setNewData(stationArr);
        //巡检项目 默认第一个
        if (stationArr.size() > 0) {
            taskItems.addAll(stationArr.get(0).getItem());
            taskAdapter.setNewData(taskItems);
        }
    }

    @OnClick({R.id.more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more:
                //巡检单审核
                mDialogFrament = HxSationDialogFragment.newInstance();
                Bundle bundle = new Bundle();
                bundle.putBoolean(Constants.DIALOG_IS_PHONE,false);
                if (taskType == 4) {
                    bundle.putString(Constants.DIALOG_CANCLE_STR, "取消");
                    bundle.putString(Constants.DIALOG_UPLOADBTN_STR, "确认归档");
                } else {
                    bundle.putString(Constants.DIALOG_CANCLE_STR, "不通过");
                    bundle.putString(Constants.DIALOG_UPLOADBTN_STR, "通过");
                }
                mDialogFrament.setArguments(bundle);
                mDialogFrament.show(getFragmentManager(), "image");
                mDialogFrament.setLoadLisetener(new HxSationDialogFragment.UpLoadLisetener() {
                    @Override
                    public void upload() {
                        if (taskType == 4) {
                             apiExamineTask(mDialogFrament.getDes(), 0);
                        } else {
                            //同意  0通过 1不通过
                             apiTaskCheck(mDialogFrament.getDes(), 0);
                        }
                    }
                });
                mDialogFrament.setCancleLisetener(new HxSationDialogFragment.CancleLisetener() {
                    @Override
                    public void cancle() {
                        mDialogFrament.dismiss();
                        if (taskType == 4) {
                            return;
                        }
                        if (!TextUtils.isEmpty(mDialogFrament.getDes())) {
                              apiTaskCheck(mDialogFrament.getDes(), 1);
                        } else {
                            ToastUtil.showToast("请填写不通过的原因");
                        }
                    }
                });
                break;
        }
    }

    /**
     * 审核提交
     *
     * @param des
     * @param checkType
     */
    private void apiTaskCheck(String des, int checkType) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().getTaskCheck(taskId, checkType, des);
        autoClose(call);
        android.util.Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO dto = response.body();
                if (response.isSuccessful()) {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    finish();
                } else {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    ToastUtil.showToast("数据异常，请重新审核");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ---->" + t);
                ToastUtil.showToast("网络请求失败，请重新审核");
            }
        });
    }


    /**
     * 考核归档
     *
     * @param des
     * @param checkType
     */
    private void apiExamineTask(String des, int checkType) {
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().getExamineTask(taskId, des);
        autoClose(call);
        android.util.Log.d(TAG, "ApiRequestData: " + call.request().url());
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO dto = response.body();
                if (response.isSuccessful()) {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    finish();
                } else {
                    if (dto != null) {
                        ToastUtil.showToast(dto.getMsg());
                    }
                    ToastUtil.showToast("数据异常，请重新审核");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                android.util.Log.d(TAG, "onFailure: ---->" + t);
                ToastUtil.showToast("网络请求失败，请重新审核");
            }
        });
    }

}
